package com.bbx.demo.broadcast;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

/**
 *广播模式
 * 1、第二个及以后的客户端上线后，其他客户端能收到上线消息，
 * 2、客户端下线后能收到服务端发来的客户端下线消息
 * 3、客户端发送消息后 ，发送着收到的消息  显示是 自己， 其他客户端收到的信息显示发送者的端口
 */
public class BroadcastServer {

    private int port = 8091;

    public BroadcastServer() {
    }

    public static void main(String[] args) throws InterruptedException {
        BroadcastServerHandler broadcastServerHandler1 = new BroadcastServerHandler();
        new BroadcastServer().start(broadcastServerHandler1);

    }

    private void start(ChannelHandler broadcastServerHandler ) throws InterruptedException {
        NioEventLoopGroup bossEventExecutors = new NioEventLoopGroup();
        NioEventLoopGroup workerEventExecutors = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossEventExecutors, workerEventExecutors)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new StringDecoder(CharsetUtil.UTF_8)).addLast(new StringEncoder(CharsetUtil.UTF_8)).addLast(broadcastServerHandler);
                        }
                    });
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossEventExecutors.shutdownGracefully();
            workerEventExecutors.shutdownGracefully();
        }


    }


}
